import 'package:auto_route/annotations.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:intl/intl.dart';
import 'package:sonora/bloc/mine/sj_mine_bloc.dart';
import 'package:sonora/bloc/mine/sj_mine_event.dart';
import 'package:sonora/bloc/mine/sj_mine_state.dart';
import 'package:sonora/config/sj_app_initial.dart';
import 'package:sonora/models/sj_country_data.dart';
import 'package:sonora/shared/lib/constants/sj_colors.dart';
import 'package:sonora/utils/sj_country_utils.dart';
import 'package:sonora/utils/sj_device_utils.dart';
import 'package:sonora/utils/sj_log_utils.dart';
import 'package:sonora/utils/sj_screen_utils.dart';
import 'package:sonora/utils/sj_text_style.dart';
import 'package:sonora/views/appbar/sj_appbar.dart';

import '../models/sj_content_more_item_data.dart';
import 'bottom_sheet/sj_bottom_sheet_view.dart';

@RoutePage()
class SjEditPage extends StatefulWidget {
  const SjEditPage({super.key});
  @override
  State<SjEditPage> createState() => _SjEditPageState();
}

class _SjEditPageState extends State<SjEditPage> {
  late final SjMineBloc _mineBloc = getit<SjMineBloc>();
  final TextEditingController _editingController = TextEditingController();
  final FixedExtentScrollController _scrollController =
      FixedExtentScrollController();
  final List<SjCountryData> countryList =
      SjCountryUtils.instance.countryList ?? [];
  @override
  void initState() {
    _mineBloc.add(const SjMineEventLoadedUserInfo());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        extendBodyBehindAppBar: true, // 使内容延伸到导航
        appBar: SjAppbar(
          title: const Text(
            '',
            style: SjTextStyle.customFontBlack20,
          ),
          backgroundColor: Colors.transparent, // 设置导航栏背景为透明
          elevation: 0, // 去除导航栏阴影
          leading: IconButton(
            icon: Image.asset('assets/images/nav_back.png'), // 左侧按钮
            onPressed: () {
              // 处理返回逻辑
              _mineBloc.add(const SjMineEvent.pagePop());
              Navigator.of(context).pop();
            },
          ),
        ),
        body: BlocProvider.value(
            value: _mineBloc,
            child: Container(
              // height: double.infinity,
              padding: const EdgeInsets.symmetric(horizontal: 32),
              width: double.infinity,
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/profile_bg_other.png'),
                  fit: BoxFit.cover,
                ),
              ),
              child: SafeArea(
                  child: Column(
                children: [
                  Expanded(
                      child: SingleChildScrollView(
                    physics: const NeverScrollableScrollPhysics(),
                    child: Column(children: [
                      const SizedBox(
                        height: 44,
                      ),
                      Stack(
                        children: [
                          BlocBuilder<SjMineBloc, SjMineState>(
                              builder: (context, state) {
                            return Container(
                              width: 98, // Diameter (2 * radius) = 2 * 15
                              height: 98, // Diameter (2 * radius) = 2 * 15
                              decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                image: state.headerImage != null
                                    ? DecorationImage(
                                        image: AssetImage(state.headerImage ??
                                            ''), // Replace with your avatar image URL
                                        fit: BoxFit.cover,
                                      )
                                    : DecorationImage(
                                        image: NetworkImage(
                                            state.userInfoData?.avatarUrl ??
                                                ''),
                                        fit: BoxFit.cover),
                                border: Border.all(
                                  color: SjColors.whiteColor, // Border color
                                  width: 2, // Border width
                                ),
                              ),
                            );
                          }),
                          Positioned(
                              right: 6,
                              bottom: 0,
                              child: InkWell(
                                child: Image.asset(
                                    'assets/images/edit_camera_icon.png'),
                                onTap: () {
                                  showMenu();
                                  SjLogPvManger.stat(
                                      page: SjLogPages.sjActionNameEditavatar);
                                },
                              ))
                        ],
                      ),
                      const SizedBox(
                        height: 35,
                      ),
                      Container(
                        padding: const EdgeInsets.fromLTRB(20, 5, 20, 2),
                        decoration: const BoxDecoration(
                          color: SjColors.themeBColor,
                          borderRadius: BorderRadius.all(Radius.circular(12.0)),
                        ),
                        child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              const Text(
                                'Nick Name',
                                style: SjTextStyle.customFontBlack16,
                              ),
                              Expanded(
                                  child: BlocBuilder<SjMineBloc, SjMineState>(
                                builder: (context, state) {
                                  final String nickName =
                                      state.userInfoData?.nickname ?? '';
                                  _editingController.text = nickName;
                                  return TextFormField(
                                    controller: _editingController,
                                    decoration: const InputDecoration(
                                        enabledBorder: InputBorder.none,
                                        focusedBorder: InputBorder.none),
                                    textAlign: TextAlign.end,
                                    cursorColor: SjColors.themeColor,
                                    style: SjTextStyle.customFontBlack16,
                                    onFieldSubmitted: (_) {
                                      FocusScope.of(context)
                                          .unfocus(); // Dismiss keyboard on submit
                                    },
                                    onEditingComplete: () {
                                      _mineBloc.add(SjMineEventNickNameChanged(
                                          nickName: _editingController.text));
                                    },
                                  );
                                },
                              ))
                            ]),
                      ),
                      const SizedBox(
                        height: 24,
                      ),
                      BlocBuilder<SjMineBloc, SjMineState>(
                          builder: (context, state) {
                        return InkWell(
                          child: Container(
                            padding: const EdgeInsets.fromLTRB(20, 14, 20, 12),
                            decoration: const BoxDecoration(
                              color: SjColors.themeBColor,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(12.0)),
                            ),
                            child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  const Text(
                                    'Date Of Birth',
                                    style: SjTextStyle.customFontBlack16,
                                  ),
                                  Text(
                                    '${state.userInfoData?.birthday}',
                                    style: SjTextStyle.customFontBlack16,
                                  )
                                ]),
                          ),
                          onTap: () {
                            _showDatePicker(
                                context, state.userInfoData?.birthday);
                          },
                        );
                      }),
                      const SizedBox(
                        height: 24,
                      ),
                      BlocBuilder<SjMineBloc, SjMineState>(
                          builder: (context, state) {
                        return InkWell(
                          child: Container(
                            padding: const EdgeInsets.fromLTRB(20, 14, 20, 12),
                            decoration: const BoxDecoration(
                              color: SjColors.themeBColor,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(12.0)),
                            ),
                            child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  const Text(
                                    'Country',
                                    style: SjTextStyle.customFontBlack16,
                                  ),
                                  Text(
                                    '${state.userInfoData?.country}',
                                    style: SjTextStyle.customFontBlack16,
                                  )
                                ]),
                          ),
                          onTap: () {
                            _showCountryPicker(
                                context, state.userInfoData?.country);
                          },
                        );
                      }),
                      const SizedBox(
                        height: 150,
                      ),
                      BlocBuilder<SjMineBloc, SjMineState>(
                          builder: (context, state) {
                        return InkWell(
                          child: Container(
                            height: 47,
                            margin: const EdgeInsets.symmetric(horizontal: 16),
                            decoration: BoxDecoration(
                              // color: SjColors.blackColor,
                              color: state.isEdit
                                  ? SjColors.blackColor
                                  : SjColors.blackColor99,
                              borderRadius:
                                  const BorderRadius.all(Radius.circular(27.0)),
                            ),
                            child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: const [
                                  Text(
                                    'SUBMIT',
                                    style: SjTextStyle.customFontTheme16,
                                  ),
                                ]),
                          ),
                          onTap: () {
                            if (!state.isEdit) return;
                            _mineBloc.add(const SjMineEventSaveUserInfo());
                          },
                        );
                      }),
                    ]),
                  ))
                ],
              )),
            )));
  }

  // 显示底部弹出的日期选择器
  void _showDatePicker(BuildContext context, String? birthday) {
    DateTime tempPickedDate = DateTime.now(); // 默认选中1989-10-02
    if (birthday != null) {
      tempPickedDate = DateTime.parse(birthday);
    }
    showModalBottomSheet(
      context: context,
      builder: (BuildContext builder) {
        return SizedBox(
          height: MediaQuery.of(context).size.height / 3,
          child: Column(
            children: [
              SizedBox(
                height: MediaQuery.of(context).size.height / 4,
                child: CupertinoDatePicker(
                  mode: CupertinoDatePickerMode.date,
                  initialDateTime: tempPickedDate,
                  minimumDate: DateTime(1900), // 最小可选日期
                  maximumDate: DateTime.now().subtract(
                      const Duration(days: 18 * 365)), // 最大可选日期为今天减去18年
                  onDateTimeChanged: (DateTime newDate) {
                    tempPickedDate = newDate; // 临时保存用户选择的日期
                  },
                ),
              ),
              // 确认按钮
              InkWell(
                child: Container(
                  height: 47,
                  margin: const EdgeInsets.symmetric(horizontal: 48),
                  decoration: const BoxDecoration(
                    color: SjColors.blackColor,
                    borderRadius: BorderRadius.all(Radius.circular(27.0)),
                  ),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: const [
                        Text(
                          'Confirm',
                          style: SjTextStyle.customFontTheme16,
                        ),
                      ]),
                ),
                onTap: () {
                  String formattedDate =
                      DateFormat('yyyy-MM-dd').format(tempPickedDate);
                  _mineBloc
                      .add(SjMineEventBirthdayChanged(birthday: formattedDate));
                  Navigator.pop(context); // 关闭底部弹出框
                },
              )
            ],
          ),
        );
      },
    );
  }

  // 显示类似时间选择器的国家选择器
  void _showCountryPicker(BuildContext mContext, String? selectedCountry) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final index =
          countryList.indexWhere((element) => element.name == selectedCountry);
      if (index != -1) {
        _scrollController.jumpTo(index * 60.0);
      }
    });
    showModalBottomSheet(
      context: mContext,
      builder: (BuildContext builder) {
        return StatefulBuilder(
          builder: (BuildContext context, StateSetter setStateModal) {
            return Column(
              children: [
                const SizedBox(height: 30),
                Expanded(
                  child: SizedBox(
                    height: MediaQuery.of(context).size.height / 3,
                    child: ListWheelScrollView.useDelegate(
                      controller: _scrollController,
                      itemExtent: 60,
                      perspective: 0.001,
                      diameterRatio: 1.6,
                      physics: const FixedExtentScrollPhysics(),
                      squeeze: 1.0,
                      overAndUnderCenterOpacity: 0.2,
                      useMagnifier: true,
                      magnification: 1.3,
                      onSelectedItemChanged: (index) {
                        selectedCountry = countryList[index].name;
                      },
                      childDelegate: ListWheelChildBuilderDelegate(
                        childCount: countryList.length,
                        builder: (context, index) {
                          return Text(countryList[index].name ?? '');
                        },
                      ),
                    ),
                  ),
                ),
                // 确认按钮
                InkWell(
                  child: Container(
                    height: 47,
                    margin: const EdgeInsets.symmetric(horizontal: 48),
                    decoration: const BoxDecoration(
                      color: SjColors.blackColor,
                      borderRadius: BorderRadius.all(Radius.circular(27.0)),
                    ),
                    child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: const [
                          Text(
                            'Confirm',
                            style: SjTextStyle.customFontTheme16,
                          ),
                        ]),
                  ),
                  onTap: () {
                    _mineBloc.add(SjMineEventCountryChanged(
                        country: selectedCountry ?? ''));
                    Navigator.pop(context); // 关闭底部弹出框
                  },
                ),
                SizedBox(height: SjScreenUtils.getBottomSaveHeight(context)),
              ],
            );
          },
        );
      },
    );
  }

  // 显示交互菜单
  void showMenu() {
    final List<Map<String, dynamic>> list0 = [
      {'name': 'Album', 'type': 1},
      {'name': 'Camera', 'type': 2},
    ];
    final list = list0.map((e) => SjContentMoreItemData.fromJson(e)).toList();
    SjBottomSheetView.show(
        context: context, options: list, onOptionSelected: _onOptionSelected);
  }

  void _onOptionSelected(BuildContext context, SjContentMoreItemData moreItem) {
    if (moreItem.type == 1) {
      _mineBloc.add(const SjMineEventAddHeaderImage());
    } else if (moreItem.type == 2) {
      _mineBloc.add(const SjMineEventTakePhoto());
    }
  }
}
